/**
 * @created by kongqf on 2019-12-17 13:54:46
 * @updated by
 * @description wfdemo
 */
/* eslint no-undef:0 */
/* eslint new-cap:0 */

define([
  './libs/mxgraph/libs/init.js',
  './libs/mxgraph/mxClient.js',
  './pages/workflow/studio/nwflist/jWorkflow/jobFlowGraph.css',
  './libs/mxgraph/libs/sanitizer.min.js',
  './libs/mxgraph/libs/editorUi.js',
  './libs/mxgraph/libs/editor.js',
  './libs/mxgraph/libs/sidebar.js',
  './libs/mxgraph/libs/graph.js',
  './libs/mxgraph/libs/format.js',
  './libs/mxgraph/libs/shapes.js',
  './libs/mxgraph/libs/actions.js',
  './libs/mxgraph/libs/menus.js',
  './libs/mxgraph/libs/toolbar.js',
  './libs/mxgraph/libs/dialogs.js',
  './custom/widgets/js/YuWorkflow.js',
  './pages/workflow/studio/nwflist/jWorkflow/vertex.js',
  './pages/workflow/studio/nwflist/jWorkflow/edge.js',
  './pages/workflow/studio/nwflist/jWorkflow/wf.js',
  './pages/workflow/studio/nwflist/jWorkflow/nodeType.js',
  './custom/widgets/js/YufpUserSelectDialog.js',
  './custom/widgets/js/YufpCopyUserSelector.js',
  './custom/widgets/js/YufpNodeScriptEditor.js',
  './custom/widgets/js/YufpSubIdSelector.js'
], function (require, exports) {
  /**
   * 页面加载完成时触发
   * @param hashCode 路由ID
   * @param data 传递数据对象
   * @param cite 页面站点信息
   */
  exports.ready = function (hashCode, data, cite) {
    var size = yufp.frame.size();
    yufp.custom.vue({
      el: cite.el,
      data: function () {
        return {
          // height: size.height - 102,
          height: size.height - 59,
          toolbarItems: [],
          value2: 100,
          viewScale: '100%',
          options: [{key: 10, value: '10%'}, {key: 20, value: '20%'}, {key: 30, value: '30%'}, {key: 40, value: '40%'}, {key: 50, value: '50%'}, {key: 60, value: '60%'}, {key: 70, value: '70%'}, {key: 80, value: '80%'}, {key: 90, value: '90%'}, {key: 100, value: '100%'}],
          activeName: ['0'], // 如果要展开，直接配置对应item的name值
          graphData: null,
          formItems: {},
          showSidebar: true,
          showFormatbar: true,
          workflowData: data,
          defaultNodeData: {},
          defaultLineData: {},
          defaultDict: {},
          formatType: '',
          tmpCell: null,
          locked: false, // 是否预览模式，会自动屏蔽界面上输入操作
          formdatavertex: {},
          formdataedge: {},
          formdataworkflow: {},
          rawValue: '',
          returnBackFuncId: '',
          returnBackRootId: '',
          hasInit: false,
          comments: [],
          dialogVisible: false,
          nodeScript: ''
        };
      },
      watch: {
        formdatavertex: {
          handler: function (nVal, oldVal) {
            this.btnSaveCellData(this.hasInit);
          },
          deep: true
        },
        formdataedge: {
          handler: function (nVal, oldVal) {
            this.btnSaveCellData(this.hasInit);
          },
          deep: true
        },
        formdataworkflow: {
          handler: function (nVal, oldVal) {
            this.btnSaveCellData(this.hasInit);
          },
          deep: true
        }
      },
      mounted: function () {
        this.returnBackFuncId = data.returnBackFuncId;
        this.returnBackRootId = data.returnBackRootId;
        this.setToolbarItems();
      },
      methods: {
        // 初始化左侧示例图标
        initGraph: function () {
          if (this.locked) {
            this.hideSidebarFn();
            this.hideFormatbarFn();
          }
          this.getDict();
        },
        // 初始化绑定数据
        initData: function () {
          var _this = this;// 获取流程图
          yufp.service.request({
            url: backend.workflowService + '/api/nwfflow/' + data.flowId + '/' + data.flowSign,
            callback: function (code, msg, response) {
              console.log('获取流程图数据', response.data.flowContent);
              _this.graphData = response.data.flowContent;
              _this.graphData && (_this.workflowData = _this.$refs.refWorkflow.loadXML(_this.graphData));
              _this.formatType = 'workflow';
              _this.$nextTick(function () {
                // 初始化图信息
                _this.cellclickFn();
                if (_this.$refs.refWorkflow.getGraphAllvertex().length) {
                  _this.$refs.refWorkflow.graph.scrollCellToVisible(_this.$refs.refWorkflow.getGraphAllvertex()[parseInt(_this.$refs.refWorkflow.getGraphAllvertex().length / 2)], true);
                }
              });
            }
          });
        },
        getDict: function () {
          var _this = this;
          yufp.service.request({
            url: backend.workflowService + '/api/studio/dict',
            callback: function (code, msg, response) {
              _this.defaultDict = response;
              console.log('字典数据为', JSON.stringify(_this.defaultDict));
              // 反遍历对象数组
              _this.dealNodeProperty();
              _this.setSidebarItems();
              _this.initData();
            }
          });
        },
        // 合并表单数据,将数据从表单合并到对象
        extendFormData: function (fd, cd, exc) {
          for (var k in fd) {
            if (fd[k] !== undefined && (!exc || !exc.hasOwnProperty(k))) {
              cd[k] = fd[k];
            }
          }
          return cd;
        },
        // 处理数据，主要用于区分常规属性、可选属性、操作属性
        dealNodeProperty: function () {
          var hasAllBaseData = true;
          this.formItems = {
            base: [],
            oper: [],
            selectable: [],
            edge: [],
            wf: []
          };
          var tmp;
          // 节点属性
          if (VERTEX_PRO) {
            for (var k in VERTEX_PRO) {
              tmp = yufp.clone(VERTEX_PRO[k], {});
              // 将select数据转换
              if (tmp.type === 'select') {
                tmp.value = this.changeData2Select(tmp.key, VERTEX_PRO[k].value);
              }
              tmp.required = tmp.required || false;
              if (tmp.dist === 'base' || tmp.dist === 'oper') {
                this.formItems[tmp.dist].push(tmp);
              } else {
                this.formItems['selectable'].push(tmp);
              }
              if (tmp.defaultValue !== undefined) {
                this.defaultNodeData[k] = tmp.defaultValue;
              } else if (['nodeType', 'label'].indexOf(k) === -1) {
                this.defaultNodeData[k] = null;
              }
            }
            this.addDefaultFormItems('base');
          } else {
            hasAllBaseData = false;
          }
          // 连线属性
          if (EDGE_PRO) {
            for (var k in EDGE_PRO) {
              tmp = yufp.clone(EDGE_PRO[k], {});
              // 将select数据转换
              if (tmp.type === 'select') {
                tmp.value = this.changeData2Select(tmp.key, EDGE_PRO[k].value);
              }
              tmp.defaultValue !== undefined && (this.defaultLineData[k] = tmp.defaultValue);
              tmp.required = tmp.required || false;
              this.formItems['edge'].push(tmp);
            }
            this.addDefaultFormItems('edge');
          } else {
            hasAllBaseData = false;
          }
          // 图属性
          if (WORKFLOW_PRO) {
            for (var k in WORKFLOW_PRO) {
              tmp = yufp.clone(WORKFLOW_PRO[k], {});
              // 将select数据转换
              if (tmp.type === 'select') {
                tmp.value = this.changeData2Select(tmp.key, WORKFLOW_PRO[k].value);
              }
              tmp.defaultValue !== undefined && this.workflowData[k] !== undefined && (this.workflowData[k] = tmp.defaultValue);
              tmp.required = tmp.required || false;
              this.formItems['wf'].push(tmp);
            }
          } else {
            hasAllBaseData = false;
          }
          if (!hasAllBaseData) {
            this.$message({message: '基础数据缺失', type: 'warning'});
          }
        },
        // 将数据转换成下拉框格式
        changeData2Select: function (key, data) {
          var options = [];
          if (this.defaultDict[key]) {
            options = [];
            for (var i = 0, l = this.defaultDict[key].length; i < l; i++) {
              options.push({
                key: this.defaultDict[key][i].key,
                value: this.defaultDict[key][i].desc
              });
            }
          } else if (data && Object.prototype.toString.call(data) === '[object Object]') {
            options = [];
            for (var k in data) {
              options.push({
                key: k,
                value: data[k]
              });
            }
          }
          return options;
        },
        // 增加表单默认项
        addDefaultFormItems: function (key) {
          if (key == 'edge') {
            this.formItems[key].unshift({
              name: '路由ID',
              key: 'nid',
              type: 'input',
              readOnly: true
            });
          } else if (key == 'base') {
            this.formItems[key].unshift({
              name: '节点ID',
              key: 'nid',
              type: 'input',
              readOnly: true
            });
          }
        },
        // 获取表单输入项类型
        getFormItemCtype: function (type) {
          if (['text'].indexOf(type) > -1) {
            return 'input';
          }
          return type;
        },
        checkHiddenItem: function (type) {
          var has = false;
          this.formItems[type].forEach(function (item) {
            if (item.hidden === false) {
              has = true;
            }
          });
          return has;
        },
        // 根据节点类型切换表单字段是否显示
        changeNodeFieldHidden: function (cell) {
          if (this.formatType === 'vertex') {
            var fields = [];
            var exfields = [];
            for (var i = 0, l = NODE_TYPE.length; i < l; i++) {
              if (cell.data.nodeType === NODE_TYPE[i].nodeType) {
                exfields = NODE_TYPE[i].exfields || [];
                fields = NODE_TYPE[i].fields || [];
                break;
              }
            }
            var _this = this;
            ['base', 'oper', 'selectable'].forEach(function (t) {
              var item;
              for (var k = 0, l = _this.formItems[t].length; k < l; k++) {
                item = _this.formItems[t][k];
                if (exfields.length > 0) {
                  if (exfields.indexOf(item.key) > -1) {
                    _this.formItems[t][k].hidden = true;
                  } else {
                    _this.formItems[t][k].hidden = false;
                  }
                } else if (fields.length === 0 || fields.indexOf(item.key) > -1 || item.key === 'nid') {
                  _this.formItems[t][k].hidden = false;
                } else {
                  _this.formItems[t][k].hidden = true;
                }
              }
            });
          }
        },
        // 节点单击事件
        cellclickFn: function (cell) {
          this.hasInit = false;
          if (!this.formatType) {
            this.$nextTick(function () {
              this.$refs['refForm' + this.formatType].resetFields(1);
            });
          }
          // 切换节点点击时，默认将属性面板展开
          if (this.activeName.indexOf('0') == -1) {
            this.activeName.push('0');
          }
          this.formatType = '';
          this.$nextTick(function () {
            if (cell === undefined) {
              // 选中的是图
              this.formatType = 'workflow';
              this.$nextTick(function () {
                yufp.extend(true, this.formdataworkflow, this.workflowData);
                this.hasInit = true;
              });
            } else if (cell.vertex) {
              this.formatType = 'vertex';
              this.tmpCell = cell;
              this.changeNodeFieldHidden(cell);
              this.$nextTick(function () {
                yufp.extend(true, this.formdatavertex, cell.data);
                this.hasInit = true;
              });
            } else if (cell.edge) {
              // 连线
              this.formatType = 'edge';
              this.tmpCell = cell;
              this.$nextTick(function () {
                yufp.extend(true, this.formdataedge, cell.data);
                this.hasInit = true;
              });
            }
          });
        },
        // 添加连线
        addEdgeFn: function (cell) {
          yufp.extend(true, cell.data, this.defaultLineData);
        },
        btnSaveCellData: function (hasInit) {
          if (hasInit) {
            var formatName = 'formdata' + this.formatType;
            if (this.formatType == 'vertex' || this.formatType == 'edge') {
              // 更新节点属性信息
              this.$refs.refWorkflow.updateCell(this.tmpCell.id, 'label', this[formatName].label, this.formatType);
              this.$refs.refWorkflow.updateCell(this.tmpCell.id, 'data', this.extendFormData(this[formatName], this.tmpCell.data), this.formatType);
            } else if (this.formatType == 'workflow') {
              // 保存图数据
              this.workflowData = this.extendFormData(this[formatName], this.workflowData);
            }
          }
        },
        // 顶部工具条按钮单击事件
        toolbarItemClickFn: function (fn) {
          if (typeof fn === 'string') {
            this.$refs.refWorkflow.doAction(fn);
          } else if (typeof fn === 'function') {
            fn();
          }
        },
        // 下拉框改变缩放大小设置
        graphViewSelectChangeFn: function (val) {
          this.changeGraphViewScaleFn(parseInt(this.viewScale) / 100);
        },
        // 滑块拖动缩放设置
        graphViewSliderChangeFn: function () {
          this.changeGraphViewScaleFn(parseInt(this.value2) / 100);
        },
        resetGraphViewScaleFn: function () {
          this.changeGraphViewScaleFn(1);
        },
        // 缩放graph图
        scaleFn: function (evt) {
          var scale = evt.getProperties('scale');
          if (this.viewScale !== scale.scale) {
            this.viewScale = parseInt(scale.scale * 100) + '%';
          }
        },
        changeGraphViewScaleFn: function (v) {
          // 同时更新界面上对应的缩放值
          this.value2 = parseInt(v * 100);
          this.viewScale = this.value2 + '%';
          this.$refs.refWorkflow.graphScale(v);
        },
        // 设置左侧示例图
        setSidebarItems: function () {
          var _this = this;
          var tmpData = {};
          var items = [];
          var types = [];
          NODE_TYPE.forEach(function (item) {
            tmpData = {
              nodeType: item.nodeType,
              label: item.label || item.title
            };
            types.push(item.nodeType);
            items.push({
              img: item.img,
              title: item.title,
              data: ['S', 'E'].indexOf(item.nodeType) > -1 ? tmpData : yufp.clone(_this.defaultNodeData, tmpData)
            });
          });
          this.$refs.refWorkflow.setNodeType(types);
          this.$refs.refWorkflow.setSidebar(items);
        },
        // 设置顶部工具条按钮
        setToolbarItems: function () {
          var items = [
            [ { img: 'save', title: '保存', action: this.saveGraphXMl},
              // { img: 'auto', title: 'XML', action: 'editDiagram'},
              { img: 'xml', title: 'XML', action: this.showGraphXMl},
              { img: 'help', title: '帮助', action: 'help'}
            ],
            // [
            //   { img: 'select', title: '选择'},
            //   { img: 'edge', title: '连线'},
            //   { img: 'drag', title: '拖动'},
            //   { img: 'redo', title: '撤销', action: 'undo'},
            //   { img: 'back', title: '回退', action: 'redo'},
            //   { img: 'outline', title: '缩略图', action: 'outline'}
            // ]
          ];
          if (this.locked) {
            items = [
              [{ img: 'help', title: '帮助', action: 'help'}]
            ];
          }
          this.toolbarItems = items;
        },
        // 隐藏左侧面板
        hideSidebarFn: function () {
          this.$refs.refWorkflow.hideSidebar(this.showSidebar = !this.showSidebar);
        },
        // 隐藏右侧面板
        hideFormatbarFn: function () {
          this.$refs.refWorkflow.hideFormatbar(this.showFormatbar = !this.showFormatbar);
        },
        showGraphXMl: function () {
          var flowContent = this.$refs.refWorkflow.getXML(this.workflowData);
          if (flowContent) {
            this.dialogVisible = true;
            this.nodeScript = flowContent;
          }
        },
        dialogClose: function () {
          this.dialogVisible = false;
        },
        // 保存流程图内容
        saveGraphXMl: function () {
          var _self = this;
          var flowContent = this.$refs.refWorkflow.exportXML(this.workflowData);
          if (flowContent) {
            var param = {
              'flowId': this.workflowData.flowId,
              'flowSign': this.workflowData.flowSign,
              'flowContent': flowContent
            };
            console.log('保存数据信息', flowContent);
            yufp.service.request({
              method: 'POST',
              data: param,
              url: backend.workflowService + '/api/nwfflow/update',
              callback: function (code, msg, response) {
                if (response.data == 1) {
                  _self.$message('流程图保存成功!');
                }
              }
            });
          }
        }
      }
    });
  };

  /**
   * 页面传递消息处理
   * @param type 消息类型
   * @param message 消息内容
   */
  exports.onmessage = function (type, message, cite, vm) {
    if (type === 'active-tab') {
      vm.$refs.refWorkflow.hiddenOutlineWindow(false);
    }
    if (type === 'active-tab-self') {
      vm.$refs.refWorkflow.hiddenOutlineWindow(true);
    }
  };

  /**
   * 页面销毁时触发destroy方法
   * @param id 路由ID
   * @param cite 页面站点信息
   */
  exports.destroy = function (id, cite) {
  };
});